package com.fx.server.config;

import com.fx.server.auth.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class FxServerSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private FxAuthenticationEntryPoint fxAuthenticationEntryPoint;

    @Autowired
    private FxAccessDeniedHandler fxAccessDeniedHandler;

    @Autowired
    private FxUserDetailsService fxUserDetailsService;

    @Autowired
    private FxImageCodeCheckFilter fxImageCodeCheckFilter;

    @Autowired
    private FxJwtAuthenticationFilter fxJwtAuthenticationFilter;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests().antMatchers("/codeImage").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(fxAuthenticationEntryPoint)
                .accessDeniedHandler(fxAccessDeniedHandler)
                .and().headers().frameOptions().disable();

        http.addFilterBefore(fxImageCodeCheckFilter, UsernamePasswordAuthenticationFilter.class);
        http.addFilterBefore(fxJwtAuthenticationFilter,UsernamePasswordAuthenticationFilter.class);
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(fxUserDetailsService)
                .passwordEncoder(passwordEncoder());
    }
}
